package com.open.basic.util;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;


/**
 * @author: system
 * @Date: 2025/1/20 下午2:36
 * @Version: V1.0
 * @description: | 分页调用框架 支持远程调用 数据库调用 大文件调用
 */

public class PageGetUtil {

    private static final int DEFAULT_PAGE_SIZE = 100;

    /**
     * total
     */
    private final int total;
    /**
     * pageSize
     */
    private final int pageSize;

    /**
     * pageNum
     */
    private int pageNum;

    /**
     * 当前拉取数据总数
     */
    private int fetchDataNum;

    public PageGetUtil(int total) {
        this.total = total;
        this.pageSize = DEFAULT_PAGE_SIZE;
        this.pageNum = 1;
        this.fetchDataNum = 0;
    }


    public PageGetUtil(int total, int pageSize) {
        this.total = total;
        this.pageSize = pageSize;
        this.pageNum = 1;
        this.fetchDataNum = 0;
    }

    public PageGetUtil(int total, int pageSize, int pageNum) {
        this.total = total;
        this.pageSize = pageSize;
        this.pageNum = pageNum;
        this.fetchDataNum = 0;
    }

    /**
     * 获取所有数据
     *
     * @param fetch
     * @return
     */
    public <T> List<T> fetchAllData(BiFunction<Integer, Integer, List<T>> fetch) {
        List<T> resultList = new ArrayList<>();
        while (fetchDataNum < total) {
            List<T> tList = fetch.apply(pageNum, pageSize);
            if (tList == null || tList.isEmpty()) {
                break;
            }
            resultList.addAll(tList);
            pageNum += 1;
            fetchDataNum += tList.size();
        }
        return resultList;
    }

    /**
     * 分页处理，没有返回值，需要传递处理逻辑
     * @param biConsumer
     * @param <T>
     */
    public void pageConsumer(BiFunction<Integer, Integer, Integer> biConsumer) {
        while (fetchDataNum < total) {
            int integer = biConsumer.apply(pageNum, pageSize);
            if (integer <= 0){
                break;
            }
            pageNum += 1;
            fetchDataNum += integer;
        }
    }

    public int getFetchDataNum() {
        return fetchDataNum;
    }
}
